package backtrack;

import java.util.ArrayList;
import java.util.List;

public class Solution_131 {

    List<List<String>> res = new ArrayList<>();

    public List<List<String>> partition(String s) {
        List<String> path = new ArrayList<>();
        char[] chars = s.toCharArray();
        backtrack(chars, 0, path);
        return res;
    }

    private void backtrack(char[] s, int start, List<String> path) {
        if (start == s.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int end = start; end < s.length; end++) {
            if (isPalindrome(s, start, end)) {
                path.add(new String(s, start, end - start + 1));
                backtrack(s, end + 1, path);
                path.remove(path.size() - 1);
            }
        }
    }

    // 双指针判回文，O(1) 额外空间
    private boolean isPalindrome(char[] s, int l, int r) {
        while (l < r) {
            if (s[l++] != s[r--]) return false;
        }
        return true;
    }


    public static void main(String[] args) {
        String s = "aab";
        Solution_131 solution131 = new Solution_131();
        List<List<String>> partition = solution131.partition(s);
        partition.forEach(list -> {
            list.forEach(l -> System.out.print(l + " "));
            System.out.println();
        });
    }
}
